package com.fast.common.aspect;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Objects;

/**
 * <p>
 * 对象功能: LogAspect
 * </p>
 *
 * @author: fuxiangkai
 * @date: 2020/4/6
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    ThreadLocal<Long> startTime = new ThreadLocal<Long>();

    @Pointcut("execution(public * com.fast..*Controller.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        if (log.isDebugEnabled()) {
            log.debug("[start]");
            startTime.set(System.currentTimeMillis());
        }
        try {
            // 接收到请求，记录请求内容
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("Request::").append(request.getMethod()).append(" ").append(request.getRequestURL());
            if (ObjectUtil.isNotNull(joinPoint.getArgs())) {
                stringBuilder.append("?").append(Arrays.toString(joinPoint.getArgs()));
            }
            log.info(stringBuilder.toString());
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    @AfterReturning(returning = "result", pointcut = "webLog()")
    public void doAfterReturning(Object result) {
        // 处理完请求，返回内容
        if (ObjectUtil.isNotNull(result)) {
            log.info("Respone::{}", result);
        }
        if (log.isDebugEnabled()) {
            log.debug("[end] usetime :" + (System.currentTimeMillis() - startTime.get()) + "ms");
        }
        startTime.remove();
    }

}
